// API服务统一管理
// 提供所有后端接口的调用方法

class ApiService {
    constructor() {
        this.baseURL = 'http://localhost:8080/api';
        this.token = localStorage.getItem('authToken');
    }

    // 通用请求方法
    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                ...options.headers
            },
            ...options
        };

        // 添加认证token
        if (this.token) {
            config.headers['Authorization'] = `Bearer ${this.token}`;
        }

        try {
            const response = await fetch(url, config);
            
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
            }

            return await response.json();
        } catch (error) {
            console.error(`API请求失败 [${endpoint}]:`, error);
            throw error;
        }
    }

    // GET请求
    async get(endpoint) {
        return this.request(endpoint, { method: 'GET' });
    }

    // POST请求
    async post(endpoint, data) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    // PUT请求
    async put(endpoint, data) {
        return this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    // DELETE请求
    async delete(endpoint) {
        return this.request(endpoint, { method: 'DELETE' });
    }

    // 设置认证token
    setToken(token) {
        this.token = token;
        localStorage.setItem('authToken', token);
    }

    // 清除认证token
    clearToken() {
        this.token = null;
        localStorage.removeItem('authToken');
    }

    // ==================== 认证相关接口 ====================
    
    // 用户登录
    async login(credentials) {
        return this.post('/auth/login', credentials);
    }

    // 用户登出
    async logout() {
        return this.post('/auth/logout');
    }

    // ==================== 用户相关接口 ====================
    
    // 获取用户信息
    async getUserProfile() {
        return this.get('/user/profile');
    }

    // 获取用户状态
    async getUserStatus() {
        return this.get('/user/status');
    }

    // 获取用户密码
    async getUserPassword() {
        return this.get('/user/password');
    }

    // ==================== 系统监控接口 ====================
    
    // 获取系统心跳状态
    async getSystemHeartbeat() {
        return this.get('/system/heartbeat');
    }

    // 获取休息区占用情况
    async getSeatingOccupancy() {
        return this.get('/system/seating-occupancy');
    }

    // 获取休息区心跳状态
    async getRestAreaHeartbeat() {
        return this.get('/system/rest-area/heartbeat');
    }

    // 获取美食街心跳状态
    async getFoodStreetHeartbeat() {
        return this.get('/system/food-street/heartbeat');
    }

    // 获取摆渡车心跳状态
    async getShuttleHeartbeat() {
        return this.get('/system/shuttle/heartbeat');
    }

    // 获取出入口心跳状态
    async getEntranceExitHeartbeat() {
        return this.get('/system/entrance-exit/heartbeat');
    }

    // ==================== 激流勇进监控接口 ====================
    
    // 获取检票状态
    async getTicketStatus() {
        return this.get('/monitor/roller-coaster/ticket-status');
    }

    // 获取检票日志
    async getTicketLogs() {
        return this.get('/monitor/roller-coaster/ticket-logs');
    }

    // 获取激流勇进道具状态
    async getRollerCoasterEquipment() {
        return this.get('/monitor/roller-coaster/equipment');
    }

    // 获取手机防水袋状态
    async getPhoneBagStatus() {
        return this.get('/monitor/roller-coaster/phone-bag-status');
    }

    // ==================== VR影院监控接口 ====================
    
    // 获取VR设备状态
    async getVRDeviceStatus() {
        return this.get('/monitor/vr-cinema/device-status');
    }

    // 获取当前电影信息
    async getCurrentMovie() {
        return this.get('/monitor/vr-cinema/current-movie');
    }

    // ==================== 美食街监控接口 ====================
    
    // 获取川菜馆订单队列
    async getSichuanOrderQueue() {
        return this.get('/monitor/food-street/sichuan-order-queue');
    }

    // 获取川菜馆取餐队列
    async getSichuanPickupQueue() {
        return this.get('/monitor/food-street/sichuan-pickup-queue');
    }

    // 获取粤菜馆订单队列
    async getCantoneseOrderQueue() {
        return this.get('/monitor/food-street/cantonese-order-queue');
    }

    // 获取粤菜馆取餐队列
    async getCantonesePickupQueue() {
        return this.get('/monitor/food-street/cantonese-pickup-queue');
    }

    // 获取日料店订单队列
    async getJapaneseOrderQueue() {
        return this.get('/monitor/food-street/japanese-order-queue');
    }

    // 获取日料店取餐队列
    async getJapanesePickupQueue() {
        return this.get('/monitor/food-street/japanese-pickup-queue');
    }

    // ==================== 订餐服务接口 ====================
    
    // 提交订单
    async submitOrder(orderData) {
        return this.post('/food-order/submit', orderData);
    }

    // 获取订单历史
    async getOrderHistory() {
        return this.get('/food-order/history');
    }

    // 获取订单详情
    async getOrderDetails(orderNumber) {
        return this.get(`/food-order/details/${orderNumber}`);
    }

    // 取消订单
    async cancelOrder(orderNumber) {
        return this.post(`/food-order/cancel/${orderNumber}`);
    }

    // ==================== 游客统计接口 ====================
    
    // 获取当前游客统计
    async getCurrentVisitorStats() {
        return this.get('/visitor-statistics/current');
    }

    // 获取历史游客统计
    async getHistoricalVisitorStats() {
        return this.get('/visitor-statistics/historical');
    }

    // ==================== 项目推荐接口 ====================
    
    // 获取游客信息
    async getVisitorInfo() {
        return this.get('/project-recommend/visitor-info');
    }

    // 获取所有项目
    async getAllProjects() {
        return this.get('/project-recommend/projects');
    }

    // 获取项目推荐
    async getProjectRecommendations() {
        return this.get('/project-recommend/recommendations');
    }

    // 预约项目
    async reserveProject(projectId) {
        return this.post('/project-recommend/reserve', { projectId });
    }

    // ==================== 项目详情接口 ====================
    
    // 获取激流勇进设备状态
    async getRollerCoasterEquipment() {
        return this.get('/project/roller-coaster/equipment');
    }

    // 获取激流勇进排队信息
    async getRollerCoasterQueue() {
        return this.get('/project/roller-coaster/queue');
    }

    // 获取VR影院设备状态
    async getVRCinemaEquipment() {
        return this.get('/project/vr-cinema/equipment');
    }

    // 获取VR影院排队信息
    async getVRCinemaQueue() {
        return this.get('/project/vr-cinema/queue');
    }
}

// 创建全局API服务实例
const apiService = new ApiService();

// 导出到全局作用域
window.apiService = apiService;
